<?php
class cart_model extends CI_Model{
	function __construct(){
	parent::__construct();
	}
	
	function insert_cart($id_produk, $id_cart){
		$produk=array('id_item'=>'', 'id_cart'=>$id_cart,'id_produk'=>$id_produk);
		$this->db->insert('item_cart',$produk);		
	}
	
	function get_produk_cart($id_user){
		$sql = "SELECT * 
					FROM cart as c
					join produk as p, item_cart as ic, stok_barang as st
					WHERE c.id_user =".$id_user." and c.payment = 'No' and c.id_cart = ic.id_cart and ic.id_produk = p.id_produk and p.id_produk = st.id_produk";
		$hasil = $this->db->query($sql);
		return $hasil;
	}
	
	function delete_cart($id_item){
		$this->db->where('id_item',$id_item);		
		$this->db->delete('item_cart');
	}
	
	function make_cart($id_user){
		$sql = array('id_cart'=>'', 'id_user'=>$id_user);
		$this->db->insert('cart', $sql);
	}
	
	function insertjml($id_item, $qty){
		$this->db->where('id_item', $id_item);
		$this->db->set('qty', $qty);
		$this->db->update('item_cart');
	}
	
	function cart($id_user){
		$this->db->select('*');
		$this->db->from('cart');
		$this->db->where('id_user', $id_user);
		$this->db->where('payment', 'No');
		$hasil = $this->db->get();
		return $hasil->row();
	}
	
	function total_harga($id_item){
		$sql = "SELECT sum(ic.qty*p.harga) as total
					FROM item_cart as ic
					join produk as p
					WHERE ic.id_produk = p.id_produk and id_item =".$id_item;
		$hasil = $this->db->query($sql);
		return $hasil->row();
	}
	function update_payment($id_cart, $total){
		$this->db->where('id_cart', $id_cart);
		$this->db->set('payment', 'Yes');		
		$this->db->set('total_harga', $total);		
		$this->db->update('cart');
	}
	
	function select_stok($id_produk){
		$sql  = "select jml_produk from stok_barang where id_produk=".$id_produk;
		$select = $this->db->query($sql)->row();
		$select2 = (int) $select->jml_produk;
		return $select2;
		//var_dump($select);
	}
	 
	function update_stok($id_produk, $qty){
		$this->db->where('id_produk', $id_produk);
		$this->db->set('jml_produk', $qty );
		$query=$this->db->update('stok_barang');
	}
	
	function invoice($id_user){
	$sql = "select * 
				from produk as p left join item_cart as i on p.id_produk=i.id_produk left join cart as c on i.id_cart = c.id_cart
				where c.id_user =".$id_user." and c.payment='Yes'";
	$hasil = $this->db->query($sql);
	return $hasil;
	}
}
?>